package com.example.jmeterTest.controller;

import com.example.jmeterTest.entity.User;
import com.example.jmeterTest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/api/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 添加新用户
     */
    @PostMapping
    public Mono<ResponseEntity<User>> addUser(@RequestBody User user) {
        return userService.addUser(user)
            .map(savedUser -> new ResponseEntity<>(savedUser, HttpStatus.CREATED))
            .defaultIfEmpty(ResponseEntity.status(HttpStatus.BAD_REQUEST).build());
    }
    
    /**
     * 根据ID查询用户
     */
    @GetMapping("/{id}")
    public Mono<ResponseEntity<User>> getUserById(@PathVariable Long id) {
        return userService.getUserById(id)
            .map(user -> new ResponseEntity<>(user, HttpStatus.OK))
            .defaultIfEmpty(ResponseEntity.status(HttpStatus.NOT_FOUND).build());
    }
    
    /**
     * 更新用户信息
     */
    @PutMapping("/{id}")
    public Mono<ResponseEntity<Void>> updateUser(@PathVariable Long id, @RequestBody User user) {
        // 确保用户ID匹配
        user.setId(id);
        
        return userService.updateUser(user)
            .map(success -> success ? 
                new ResponseEntity<Void>(HttpStatus.OK) : 
                new ResponseEntity<Void>(HttpStatus.NOT_FOUND));
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Mono<ResponseEntity<Void>> deleteUser(@PathVariable Long id) {
        return userService.deleteUser(id)
            .map(success -> success ? 
                new ResponseEntity<Void>(HttpStatus.NO_CONTENT) : 
                new ResponseEntity<Void>(HttpStatus.NOT_FOUND));
    }
}